<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>订单支付 - 商品管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        .payment-container {
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
        }
        .payment-section {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        .order-info {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .payment-method {
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .payment-method:hover {
            border-color: #0d6efd;
        }
        .payment-method.selected {
            border-color: #0d6efd;
            background-color: rgba(13, 110, 253, 0.05);
        }
        .payment-method-icon {
            font-size: 24px;
            margin-right: 10px;
        }
        .qr-code {
            width: 200px;
            height: 200px;
            border: 1px solid #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto;
        }
        .countdown {
            font-size: 18px;
            color: #dc3545;
            text-align: center;
            margin: 15px 0;
        }
        .payment-result {
            text-align: center;
            padding: 30px 0;
        }
        .payment-result-icon {
            font-size: 64px;
            margin-bottom: 20px;
        }
        .payment-result.success .payment-result-icon {
            color: #28a745;
        }
        .payment-result.failed .payment-result-icon {
            color: #dc3545;
        }
        .product-item {
            display: flex;
            align-items: center;
            padding: 10px 0;
            border-bottom: 1px solid #e9ecef;
        }
        .product-item:last-child {
            border-bottom: none;
        }
        .product-image {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 10px;
        }
        .product-info {
            flex: 1;
        }
        .steps {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        .step {
            text-align: center;
            flex: 1;
            position: relative;
        }
        .step::after {
            content: '';
            position: absolute;
            top: 15px;
            right: -50%;
            width: 100%;
            height: 2px;
            background-color: #e9ecef;
            z-index: 1;
        }
        .step:last-child::after {
            display: none;
        }
        .step.active .step-icon {
            background-color: #0d6efd;
            color: white;
        }
        .step.completed .step-icon {
            background-color: #28a745;
            color: white;
        }
        .step.active .step-text,
        .step.completed .step-text {
            color: #0d6efd;
        }
        .step-icon {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #e9ecef;
            color: #6c757d;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 8px;
            position: relative;
            z-index: 2;
        }
        .step-text {
            font-size: 14px;
            color: #6c757d;
        }
        .payment-btn {
            width: 100%;
            padding: 12px;
            font-size: 16px;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{shop/fragments :: navbar}"></nav>
    
    <div class="payment-container">
        <h2 class="mb-4">订单支付</h2>
        
        <!-- 步骤指示器 -->
        <div class="steps">
            <div class="step completed">
                <div class="step-icon"><i class="bi bi-check"></i></div>
                <div class="step-text">确认订单信息</div>
            </div>
            <div class="step active">
                <div class="step-icon">2</div>
                <div class="step-text">支付订单</div>
            </div>
            <div class="step">
                <div class="step-icon">3</div>
                <div class="step-text">支付成功</div>
            </div>
        </div>
        
        <!-- 订单信息 -->
        <div class="payment-section">
            <h5 class="mb-3">订单信息</h5>
            
            <div class="order-info">
                <div class="row mb-2">
                    <div class="col-md-6">
                        <span class="text-muted">订单号：</span>
                        <span th:text="${order.orderNumber}">订单号</span>
                    </div>
                    <div class="col-md-6">
                        <span class="text-muted">下单时间：</span>
                        <span th:text="${#temporals.format(order.createTime, 'yyyy-MM-dd HH:mm:ss')}">下单时间</span>
                    </div>
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <span class="text-muted">收货人：</span>
                        <span th:text="${order.address.name}">收货人</span>
                    </div>
                    <div class="col-md-6">
                        <span class="text-muted">联系电话：</span>
                        <span th:text="${order.address.phone}">联系电话</span>
                    </div>
                </div>
                
                <div class="mt-2">
                    <span class="text-muted">收货地址：</span>
                    <span th:text="${order.address.province + ' ' + order.address.city + ' ' + order.address.district + ' ' + order.address.detail}">收货地址</span>
                </div>
            </div>
            
            <!-- 商品列表 -->
            <h6 class="mb-3">商品清单</h6>
            <div th:each="item : ${order.items}" class="product-item">
                <img th:src="${item.productImage}" alt="商品图片" class="product-image">
                <div class="product-info">
                    <div th:text="${item.productName}">商品名称</div>
                    <div class="text-muted small" th:text="${item.specification}">商品规格</div>
                    <div class="d-flex justify-content-between mt-1">
                        <div>
                            <span class="text-muted">单价：</span>
                            ¥<span th:text="${#numbers.formatDecimal(item.price, 1, 2)}">0.00</span>
                        </div>
                        <div>
                            <span class="text-muted">数量：</span>
                            <span th:text="${item.quantity}">1</span>
                        </div>
                        <div>
                            <span class="text-muted">小计：</span>
                            ¥<span th:text="${#numbers.formatDecimal(item.subtotal, 1, 2)}">0.00</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="mt-3 text-end">
                <div class="d-inline-block">
                    <div class="mb-2">
                        <span class="text-muted">商品件数：</span>
                        <span th:text="${order.totalQuantity}">0</span>
                    </div>
                    <div class="mb-2">
                        <span class="text-muted">商品总价：</span>
                        ¥<span th:text="${#numbers.formatDecimal(order.totalAmount, 1, 2)}">0.00</span>
                    </div>
                    <div class="mb-2">
                        <span class="text-muted">运费：</span>
                        ¥0.00
                    </div>
                    <hr>
                    <div class="fw-bold fs-5">
                        <span class="text-muted">应付总额：</span>
                        <span class="text-danger">¥<span th:text="${#numbers.formatDecimal(order.totalAmount, 1, 2)}">0.00</span></span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 支付方式 -->
        <div class="payment-section" id="paymentMethodsSection">
            <h5 class="mb-3">选择支付方式</h5>
            
            <div class="payment-method" data-payment="alipay">
                <div class="d-flex align-items-center">
                    <i class="bi bi-alipay payment-method-icon text-primary"></i>
                    <div>
                        <div class="fw-bold">支付宝</div>
                        <div class="text-muted small">推荐使用支付宝支付，安全快捷</div>
                    </div>
                </div>
            </div>
            
            <div class="payment-method" data-payment="wechat">
                <div class="d-flex align-items-center">
                    <i class="bi bi-wechat payment-method-icon text-success"></i>
                    <div>
                        <div class="fw-bold">微信支付</div>
                        <div class="text-muted small">使用微信扫码支付</div>
                    </div>
                </div>
            </div>
            
            <div class="payment-method" data-payment="bank">
                <div class="d-flex align-items-center">
                    <i class="bi bi-credit-card payment-method-icon text-info"></i>
                    <div>
                        <div class="fw-bold">银行卡支付</div>
                        <div class="text-muted small">支持各大银行卡支付</div>
                    </div>
                </div>
            </div>
            
            <button class="btn btn-primary payment-btn mt-3" id="confirmPaymentBtn">
                确认支付
            </button>
        </div>
        
        <!-- 支付二维码 -->
        <div class="payment-section d-none" id="qrCodeSection">
            <h5 class="mb-3 text-center">扫码支付</h5>
            
            <div class="text-center mb-3">
                <span id="paymentMethodText">支付宝</span>支付
            </div>
            
            <div class="qr-code" id="qrCode">
                <i class="bi bi-qr-code" style="font-size: 100px; color: #6c757d;"></i>
            </div>
            
            <div class="countdown" id="countdown">
                支付剩余时间：<span id="countdownTime">15:00</span>
            </div>
            
            <div class="text-center mt-3">
                <p class="text-muted">请使用<span id="paymentMethodText2">支付宝</span>扫描上方二维码完成支付</p>
                <button class="btn btn-outline-secondary me-2" id="cancelPaymentBtn">取消支付</button>
                <button class="btn btn-primary" id="checkPaymentBtn">检查支付状态</button>
            </div>
        </div>
        
        <!-- 支付结果 -->
        <div class="payment-section d-none" id="paymentResultSection">
            <div class="payment-result" id="paymentResult">
                <div class="payment-result-icon">
                    <i class="bi bi-check-circle-fill" id="resultIcon"></i>
                </div>
                <h4 id="resultTitle">支付成功</h4>
                <p id="resultMessage">您的订单已支付成功，我们将尽快为您发货</p>
                <div class="mt-4">
                    <a href="/order/detail/${order.id}" class="btn btn-outline-primary me-2">查看订单详情</a>
                    <a href="/profile" class="btn btn-primary">返回个人中心</a>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{shop/fragments :: footer}"></footer>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        const orderId = /*[[${order.id}]]*/ 0;
        let selectedPaymentMethod = 'alipay';
        let countdownTimer = null;
        let checkPaymentTimer = null;
        
        // 选择支付方式
        document.querySelectorAll('.payment-method').forEach(item => {
            item.addEventListener('click', function() {
                document.querySelectorAll('.payment-method').forEach(i => i.classList.remove('selected'));
                this.classList.add('selected');
                selectedPaymentMethod = this.getAttribute('data-payment');
            });
        });
        
        // 默认选中支付宝
        document.querySelector('[data-payment="alipay"]').classList.add('selected');
        
        // 确认支付
        document.getElementById('confirmPaymentBtn').addEventListener('click', function() {
            // 显示二维码区域
            document.getElementById('paymentMethodsSection').classList.add('d-none');
            document.getElementById('qrCodeSection').classList.remove('d-none');
            
            // 更新支付方式文本
            const paymentMethodNames = {
                'alipay': '支付宝',
                'wechat': '微信',
                'bank': '银行卡'
            };
            
            document.getElementById('paymentMethodText').textContent = paymentMethodNames[selectedPaymentMethod];
            document.getElementById('paymentMethodText2').textContent = paymentMethodNames[selectedPaymentMethod];
            
            // 开始倒计时（15分钟）
            startCountdown(15 * 60);
            
            // 模拟生成二维码
            generateQRCode();
            
            // 开始检查支付状态
            startCheckPaymentStatus();
        });
        
        // 取消支付
        document.getElementById('cancelPaymentBtn').addEventListener('click', function() {
            if (confirm('确定要取消支付吗？')) {
                // 清除定时器
                if (countdownTimer) clearInterval(countdownTimer);
                if (checkPaymentTimer) clearInterval(checkPaymentTimer);
                
                // 返回支付方式选择
                document.getElementById('qrCodeSection').classList.add('d-none');
                document.getElementById('paymentMethodsSection').classList.remove('d-none');
            }
        });
        
        // 手动检查支付状态
        document.getElementById('checkPaymentBtn').addEventListener('click', checkPaymentStatus);
        
        // 生成二维码（模拟）
        function generateQRCode() {
            const qrCodeElement = document.getElementById('qrCode');
            // 这里应该调用后端API生成真实的二维码
            // 现在只是显示一个模拟的二维码
            qrCodeElement.innerHTML = `
                <div style="padding: 20px; text-align: center;">
                    <i class="bi bi-qr-code" style="font-size: 120px; color: #6c757d;"></i>
                    <p class="mt-2 text-muted">模拟二维码</p>
                    <p class="small">订单号：${/*[[${order.orderNumber}]]*/ ''}</p>
                </div>
            `;
        }
        
        // 开始倒计时
        function startCountdown(seconds) {
            let remainingSeconds = seconds;
            
            countdownTimer = setInterval(() => {
                remainingSeconds--;
                
                const minutes = Math.floor(remainingSeconds / 60);
                const secs = remainingSeconds % 60;
                document.getElementById('countdownTime').textContent = 
                    `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
                
                if (remainingSeconds <= 0) {
                    clearInterval(countdownTimer);
                    clearInterval(checkPaymentTimer);
                    
                    // 支付超时
                    showPaymentResult(false, '支付超时', '支付时间已超过15分钟，订单已取消');
                }
            }, 1000);
        }
        
        // 开始检查支付状态
        function startCheckPaymentStatus() {
            // 每5秒检查一次支付状态
            checkPaymentTimer = setInterval(checkPaymentStatus, 5000);
        }
        
        // 检查支付状态
        function checkPaymentStatus() {
            fetch(`/order/payment-status/${orderId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.paid) {
                        // 支付成功
                        clearInterval(countdownTimer);
                        clearInterval(checkPaymentTimer);
                        showPaymentResult(true, '支付成功', '您的订单已支付成功，我们将尽快为您发货');
                    }
                })
                .catch(error => {
                    console.error('检查支付状态失败:', error);
                });
        }
        
        // 显示支付结果
        function showPaymentResult(success, title, message) {
            document.getElementById('qrCodeSection').classList.add('d-none');
            document.getElementById('paymentResultSection').classList.remove('d-none');
            
            const resultElement = document.getElementById('paymentResult');
            const iconElement = document.getElementById('resultIcon');
            
            if (success) {
                resultElement.className = 'payment-result success';
                iconElement.className = 'bi bi-check-circle-fill';
            } else {
                resultElement.className = 'payment-result failed';
                iconElement.className = 'bi bi-x-circle-fill';
            }
            
            document.getElementById('resultTitle').textContent = title;
            document.getElementById('resultMessage').textContent = message;
            
            // 更新按钮链接
            if (success) {
                document.querySelector('#paymentResultSection a[href^="/order/detail"]').href = `/order/detail/${orderId}`;
            }
        }
        
        // Toast提示函数
        function showToast(message, type = 'info') {
            // 创建toast容器（如果不存在）
            let toastContainer = document.getElementById('toastContainer');
            if (!toastContainer) {
                toastContainer = document.createElement('div');
                toastContainer.id = 'toastContainer';
                toastContainer.style.position = 'fixed';
                toastContainer.style.top = '20px';
                toastContainer.style.right = '20px';
                toastContainer.style.zIndex = '1050';
                document.body.appendChild(toastContainer);
            }
            
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `toast align-items-center text-white bg-${type === 'danger' ? 'danger' : type === 'warning' ? 'warning' : type === 'success' ? 'success' : 'primary'}`;
            toast.setAttribute('role', 'alert');
            toast.setAttribute('aria-live', 'assertive');
            toast.setAttribute('aria-atomic', 'true');
            
            toast.innerHTML = `
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            `;
            
            // 添加到容器
            toastContainer.appendChild(toast);
            
            // 初始化toast
            const bsToast = new bootstrap.Toast(toast, {
                autohide: true,
                delay: 3000
            });
            
            // 显示toast
            bsToast.show();
            
            // 监听隐藏事件，移除元素
            toast.addEventListener('hidden.bs.toast', function() {
                toast.remove();
            });
        }
    </script>
</body>
</html>